<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

import { findCompany, reviewCompany } from '@/api/company'

// 表单数据
const formData = ref({
  id: null,
  name: '',
  tel: '',
  email: '',
  briefIntro: '',
  img: '',
  qrcode: ''
});


const isEditing = ref(true); // 添加编辑模式状态
const uploadRef = ref(null); // 添加上传组件引用

const rules = ref({
  name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入公司地址', trigger: 'blur' }],
  tel: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^\d{11}$/, message: '请输入11位电话号码', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入公司邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
  ],
  briefIntro: [{ required: true, message: '请输入公司简介', trigger: 'blur' }],
});


const save = async () => {
  try {
    // 调用 API 保存公司信息
    const res = await reviewCompany(formData.value); // 假设 API 方法是 updateCompany
    if (res.code === 200) { // 假设 API 返回 { code: 200, message: "success" }
      ElMessage.success('保存成功');
      isEditing.value = false; // 取消编辑模式（如果需要）
    } else {
      ElMessage.error(res.message || '保存失败');
    }
  } catch (error) {
    ElMessage.error('保存失败，请重试');
    console.error(error);
  }
};

const cancel = () => {
  isEditing.value = false;
  fetchCompanyInfo();
};

const handleUpload = async (file) => {
  const formData = new FormData();
  formData.append('file', file.file);
  try {
    const response = await fetch('/api/upload', {
      method: 'POST',
      body: formData
    });
    const result = await response.json();
    formData.value.img = result.path;
    ElMessage.success('图片上传成功');
  } catch (error) {
    ElMessage.error('图片上传失败');
    console.error(error);
  }
};
//图片上传
const triggerUpload = () => {
  if (uploadRef.value) {
    uploadRef.value.$el.querySelector('input[type="file"]').click();
  }
};


onMounted(() => {
  fetchCompanyInfo();
});

const fetchCompanyInfo = async () => {
  try {
    const res = await findCompany();
    if (res.code === 200) {
      formData.value = res.data;
      // 确保数据结构一致，如果后端返回的是 image 而不是 logo
      if (res.data.image && !res.data.img) {
        formData.value.img = res.data.image;
      }
    } else {
      ElMessage.error('获取公司信息失败');
    }
  } catch (err) {
    console.error(err.message);
    ElMessage.error('网络错误，请稍后重试！');
  }
};

</script>

<template>
  <div>
    <div>
      <h1>公司信息管理</h1>

      <!-- 编辑模式 -->
      <el-form :model="formData" :rules="rules" class="space-y-4" label-position="top">
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入公司名称"></el-input>
        </el-form-item>
        <el-form-item label="公司地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入公司地址"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.tel" placeholder="请输入11位电话号码"></el-input>
        </el-form-item>
        <el-form-item label="公司邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="公司简介" prop="briefIntro">
          <el-input v-model="formData.briefIntro" type="textarea" placeholder="请输入公司简介"></el-input>
        </el-form-item>
        <el-form-item label="公司Logo">
          <el-upload
            ref="uploadRef"
            :http-request="handleUpload"
            :show-file-list="false"
            accept="image/*"
          >
            <img v-if="formData.img" :src="formData.img" @click="triggerUpload"/>
            <el-button v-else type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="公司二维码">
          <el-upload
            ref="uploadRef"
            :http-request="handleUpload"
            :show-file-list="false"
            accept="image/*"
          >
            <img v-if="formData.qrcode" :src="formData.qrcode" @click="triggerUpload"/>
            <el-button v-else type="primary">上传公司二维码</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="save">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>

</template>

<style scoped>

</style>
